package com.mongo.data.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class JsonUtils {

    public static ObjectMapper objectMapper = ObjectMapperFactory.getContext(null);

    public static ObjectMapper objectMapperAlways = ObjectMapperFactory.getContext();

    /**
     * 对象转json
     */
    public static String objectToJson(Object obj) {
        String str = null;
        try {
            str = objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            log.error("对象转json出错", e);
        }
        return str;
    }

    /**
     * 对象转json,不忽略null属性
     */
    public static String objectToJsonContainNull(Object obj) {
        String str = null;
        try {
            str = objectMapperAlways.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            log.error("对象转json出错", e);
        }
        return str;
    }

    /**
     * json转对象
     */
    @SuppressWarnings("unchecked")
    public static <T> T jsonToObject(String json, Class<T> clazz) {
        Object obj = null;
        try {
            obj = objectMapper.readValue(json, clazz);
        } catch (Exception e) {
            log.error("json转对象出错", e);
        }
        return (T) obj;
    }

    /**
     * json转对象
     */
    @SuppressWarnings("unchecked")
    public static <T> T jsonToObject(String json, TypeReference<T> valueTypeRef) {
        Object obj = null;
        try {
            obj = objectMapper.readValue(json, valueTypeRef);
        } catch (Exception e) {
            log.error("json转对象出错", e);
        }
        return (T) obj;
    }

    /**
     * json转List
     */
    public static <T> List<T> jsonToList(String json, Class<T> clazz) {
        List<T> list = null;
        try {
            list = objectMapper.readValue(json,
                    objectMapper.getTypeFactory().constructParametricType(ArrayList.class, clazz));
        } catch (Exception e) {
            log.error("json转list出错", e);
        }
        return list;
    }

    /**
     * json转Map
     */
    public static <K, V> Map<K, V> jsonToMap(String json, Class<K> clazzKey, Class<V> clazzValue) {
        Map<K, V> map = null;
        try {
            map = objectMapper.readValue(json, objectMapper.getTypeFactory()
                    .constructParametricType(HashMap.class, clazzKey, clazzValue));
        } catch (Exception e) {
            log.error("json转map出错", e);
        }
        return map;
    }

}
